<template>
  <div class="announcement-management">
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span>公告管理</span>
        <div class="header-actions">
          <el-input
            placeholder="搜索公告标题"
            v-model="searchTitle"
            clearable
            prefix-icon="el-icon-search"
            style="width: 200px; margin-right: 10px;"
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
          ></el-input>
          <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleSearch" clearable style="width: 150px; margin-right: 10px;">
            <el-option label="全部公告" value=""></el-option>
            <el-option label="已发布" value="1"></el-option>
            <el-option label="草稿" value="0"></el-option>
          </el-select>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增公告</el-button>
        </div>
      </div>
      
      <!-- 卡片列表区域 -->
      <div class="announcement-cards" v-loading="loading" element-loading-text="加载中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)">
        <el-empty v-if="announcementList.length === 0" description="暂无公告数据"></el-empty>
        
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6" v-for="item in sortedAnnouncementList" :key="item.announcementId" class="card-col">
            <el-card class="announcement-card" :class="{'published': item.status === '1'}" shadow="hover">
              <div class="card-top">
                <div class="announcement-status">
                  <el-tag :type="item.status === '1' ? 'success' : 'info'" size="small">
                    {{ item.status === '1' ? '已发布' : '草稿' }}
                  </el-tag>
                </div>
                <div class="card-id">#{{ item.announcementId }}</div>
              </div>
              
              <div class="card-body">
                <div class="card-title">
                  <i class="el-icon-bell"></i>
                  <span class="title-text">{{ item.title }}</span>
                </div>
                <div class="card-summary">{{ item.content | ellipsis }}</div>
                <div class="card-info">
                  <div class="info-item">
                    <i class="el-icon-user"></i>
                    <span>{{ item.updateUser || '管理员' }}</span>
                  </div>
                  <div class="info-item">
                    <i class="el-icon-time"></i>
                    <span>{{ formatDate(item.updateTime) }}</span>
                  </div>
                  <!-- <div class="info-item" v-if="item.status === '1'">
                    <i class="el-icon-view"></i>
                    <span>{{ item.viewCount || 0 }} 次浏览</span>
                  </div> -->
                </div>
              </div>
              
              <div class="card-footer">
                <el-tooltip content="编辑公告" placement="top" effect="light">
                  <el-button 
                    size="mini" 
                    type="primary" 
                    icon="el-icon-edit" 
                    @click.stop="handleEdit(item)"
                  >编辑</el-button>
                </el-tooltip>
                <el-tooltip :content="item.status === '1' ? '取消发布' : '发布公告'" placement="top" effect="light">
                  <el-button 
                    size="mini" 
                    :type="item.status === '1' ? 'warning' : 'success'" 
                    :icon="item.status === '1' ? 'el-icon-turn-off' : 'el-icon-check'" 
                    @click.stop="handleToggleStatus(item)"
                  >{{ item.status === '1' ? '取消发布' : '发布' }}</el-button>
                </el-tooltip>
                <el-tooltip content="删除公告" placement="top" effect="light">
                  <el-button 
                    size="mini" 
                    type="danger" 
                    icon="el-icon-delete" 
                    @click.stop="handleDelete(item)"
                  >删除</el-button>
                </el-tooltip>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[12, 24, 48, 96]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增公告' : '编辑公告'"
      :visible.sync="dialogVisible"
      width="650px"
      @close="resetForm"
    >
      <el-form :model="announcementForm" :rules="formRules" ref="announcementForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementForm.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            :rows="8"
            placeholder="请输入公告内容"
            v-model="announcementForm.content"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="announcementForm.status">
            <el-radio label="1">立即发布</el-radio>
            <el-radio label="0">保存为草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'AnnouncementManagement',
  data() {
    return {
      // 列表数据
      announcementList: [],
      // 分页相关
      pageNum: 1,
      pageSize: 12,
      total: 0,
      // 筛选条件
      searchTitle: '',
      statusFilter: '',
      // 加载状态
      loading: false,
      submitting: false,
      // 对话框控制
      dialogVisible: false,
      dialogType: 'add', // add 或 edit
      // 表单数据
      announcementForm: {
        announceId: '',
        title: '',
        content: '',
        status: '1', // 默认立即发布
        token: localStorage.getItem('token')
      },
      // 表单验证规则
      formRules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' },
          { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' },
          { min: 10, max: 2000, message: '内容长度在 10 到 2000 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    // 根据状态和创建时间排序后的公告列表
    sortedAnnouncementList() {
      const list = [...this.announcementList];
      return list.sort((a, b) => {
        // 先按状态排序：已发布的在前
        if (a.status !== b.status) {
          return a.status === '1' ? -1 : 1;
        }
        // 再按创建时间排序：新的在前
        return new Date(b.createTime) - new Date(a.createTime);
      });
    }
  },
  filters: {
    // 文本截断过滤器
    ellipsis(value) {
      if (!value) return '';
      if (value.length > 100) {
        return value.slice(0, 100) + '...';
      }
      return value;
    }
  },
  created() {
    this.getAnnouncementList();
  },
  methods: {
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 获取公告列表
    getAnnouncementList() {
      this.loading = true;
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        title: this.searchTitle,
        status: this.statusFilter,
      };
      service.get('/api/system/announcement/getAnnouncementList', {params})
        .then(res => {
          if (res.code === 200) {
            console.log(res.data);
            this.announcementList = res.data.list || [];
            this.total = res.data.total || 0;
          } else {
            this.$message.error(res.msg || '获取公告列表失败');
          }
        })
        .catch(error => {
          console.error('获取公告列表出错:', error);
          this.$message.error('网络错误，请稍后重试');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 搜索处理
    handleSearch() {
      this.pageNum = 1; // 重置为第一页
      this.getAnnouncementList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAnnouncementList();
    },
    
    // 页码改变
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getAnnouncementList();
    },
    
    // 新增公告
    handleAdd() {
      this.dialogType = 'add';
      this.announcementForm = {
        title: '',
        content: '',
        status: '1',
        token: localStorage.getItem('token')
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.announcementForm && this.$refs.announcementForm.clearValidate();
      });
    },
    
    // 编辑公告
    handleEdit(item) {
      this.dialogType = 'edit';
      this.announcementForm = {
        announcementId: item.announcementId,
        title: item.title,
        content: item.content,
        status: item.status,
        token: localStorage.getItem('token')
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.announcementForm && this.$refs.announcementForm.clearValidate();
      });
    },
    
    // 切换发布状态
    handleToggleStatus(item) {
      const newStatus = item.status === '1' ? '0' : '1';
      const statusText = newStatus === '1' ? '发布' : '取消发布';
      
      this.$confirm(`确定要${statusText}该公告吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.put('/api/system/announcement/updateStatus', {
          announcementId: item.announcementId,
          status: newStatus,
          token: localStorage.getItem('token')
        }).then(res => {
          if (res.code === 200) {
            this.$message.success(`${statusText}成功`);
            this.getAnnouncementList();
          } else {
            this.$message.error(res.msg || `${statusText}失败`);
          }
        }).catch(error => {
          console.error(`${statusText}公告出错:`, error);
          this.$message.error('网络错误，请稍后重试');
        });
      }).catch(() => {
        // 取消操作
      });
    },
    
    // 删除公告
    handleDelete(item) {
      this.$confirm('此操作将永久删除该公告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/system/announcement/deleteAnnouncement/${item.announcementId}`).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getAnnouncementList();
          } else {
            this.$message.error(res.msg || '删除失败');
          }
        }).catch(error => {
          console.error('删除公告出错:', error);
          this.$message.error('网络错误，请稍后重试');
        });
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 提交表单
    submitForm() {
      this.$refs.announcementForm.validate(valid => {
        if (valid) {
          this.submitting = true;
          
          const url = this.dialogType === 'add' ? '/api/system/announcement/addAnnouncement' : '/api/system/announcement/updateAnnouncement';
          const api = this.dialogType === 'add' ? service.post(url, this.announcementForm) : service.put(url, this.announcementForm);
          api.then(res => {
              if (res.code === 200) {
                this.$message.success(this.dialogType === 'add' ? '添加成功' : '更新成功');
                this.dialogVisible = false;
                this.getAnnouncementList();
              } else {
                this.$message.error(res.msg || (this.dialogType === 'add' ? '添加失败' : '更新失败'));
              }
            })
            .catch(error => {
              console.error(this.dialogType === 'add' ? '添加公告出错:' : '更新公告出错:', error);
              this.$message.error('网络错误，请稍后重试');
            })
            .finally(() => {
              this.submitting = false;
            });
        }
      });
    },
    
    // 重置表单
    resetForm() {
      this.announcementForm = {
        announceId: '',
        title: '',
        content: '',
        status: '1',
        token: localStorage.getItem('token')
      };
      this.$nextTick(() => {
        this.$refs.announcementForm && this.$refs.announcementForm.clearValidate();
      });
    }
  }
};
</script>

<style scoped>
.announcement-management {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.announcement-cards {
  min-height: 300px;
  margin-bottom: 20px;
}

.card-col {
  margin-bottom: 20px;
}

.announcement-card {
  height: 100%;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.announcement-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

/* .published {
  border-left: 4px solid #67C23A;
} */

.card-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.card-id {
  font-size: 12px;
  color: #999;
}

.card-body {
  margin-bottom: 15px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.card-title i {
  margin-right: 8px;
  color: #409EFF;
}

.title-text {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-summary {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
  height: 60px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

.card-info {
  display: flex;
  flex-wrap: wrap;
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.info-item {
  margin-right: 15px;
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.info-item i {
  margin-right: 5px;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media screen and (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    align-items: flex-end;
  }
  
  .header-actions > * {
    margin-bottom: 10px;
    width: 100% !important;
  }
  
  .card-footer {
    flex-wrap: wrap;
  }
  
  .card-footer .el-button {
    margin-bottom: 5px;
  }
}
</style>
